<?php


namespace App\Utils;


class Parser
{

    public static function formParser(array $elementDatas, $authorId = 0, $pageSqId = '') {
        if (!$elementDatas) {
            return [];
        }
        $forms = [];
        $formIds = [];
        foreach ($elementDatas as $elementData){
            if($elementData['name'] == 'form'){
                $formData = $elementData['data'];
                if(in_array($formData['id'], $formIds)){
                    continue;
                }
                $item = [
                    'form_id' => $formData['id'],
                    'name'    => $formData['label'],
                    'user_id' => $authorId,
                    'page_sq_id' => $pageSqId
                ];
                $components = $formData['components'];
                $fields = [];
                foreach ($components as $component){
                    $componentData = $component['data'];
                    if(!isset($componentData['fieldName'])){
                        continue;
                    }
                    $fields[] = [
                        'field' => $componentData['fieldName'],
                        'label' => $componentData['label']
                    ];
                }
                $item['fields'] = json_encode($fields, JSON_UNESCAPED_SLASHES);
                $forms[] = $item;
                $formIds[] = $item['form_id'];
            }
        }
        return $forms;
    }
}
